package com.gui.juc.base.safe;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class SellTicketDemo {

    public static void main(String[] args) throws InterruptedException {
        TicketApp app = new TicketApp(10000);
        CountDownLatch latch = new CountDownLatch(100);
        AtomicInteger atomicInteger = new AtomicInteger(0);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                int buyCount = RandomUtil.randomInt(1, 5);
                int sellCount = app.sellTicket(buyCount);
                atomicInteger.getAndAdd(sellCount);
                latch.countDown();
            }).start();
        }
        latch.await();
        log.debug("票卖完咯，卖出的票数为：【{}】", atomicInteger.get());
        log.debug("票卖完咯，余票数为：【{}】", app.get());
        log.debug("加起来：{}", atomicInteger.get() + app.get());
    }
}


@Slf4j
class TicketApp {

    private int ticketCount;

    public TicketApp(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    public int get() {
        return this.ticketCount;
    }

    public int sellTicket(int count) {
        if (this.ticketCount >= count) {
            this.ticketCount = this.ticketCount - count;
            return count;
        } else {
            return 0;
        }
    }

}
